#!/bin/bash

# 设置脚本全局变量
# 获取当前目录下的第一个 .podspec 文件
PODSPEC_FILE=$(ls *.podspec 2>/dev/null | head -n 1)
# CHANGELOG.md 文件名
CHANGELOG_FILE=CHANGELOG.md 
# spec仓库名
LOVENSE_IOS_REPO_NAME="lovense-ios-components"


# 颜色输出函数
function echo_color_red() {
    echo -e "\033[31m$1\033[0m"
}

function echo_color_green() {
    echo -e "\033[32m$1\033[0m"
}

function echo_color_black() {
    echo -e "\033[37m$1\033[0m"
}


# 定义一个函数来验证 Swift Package
function validate_swift_package() {

    echo_color_black "Begin built swift package libraries"
    
    local package_file="./Package.swift"  # 构造当前目录下的 Package.swift 文件路径

    # 检查 Package.swift 文件是否存在
    if [[ ! -f "$package_file" ]]; then
        echo_color_red "Error: Package.swift file does not exist in the current directory."
        exit 1
    fi

    # 获取所有库名称
    LIBRARIES=$(swift package dump-package | jq -r '.products[].name')

    # 检查 LIBRARIES 是否为空
    if [ -z "$LIBRARIES" ]; then
        echo_color_red "Error: No libraries found in the package."
        exit 1
    fi
    
    # 获取第一个可用的 iOS 模拟器作为 destination
    destination=$(xcrun simctl list devices | grep -E 'iPhone|iPad' | grep -E 'Booted|Shutdown' | head -n 1 | awk -F '[()]' '{print $2}' | xargs -I {} echo "platform=iOS Simulator,id={}")

    # 编译每个库
    for LIBRARY in $LIBRARIES; do
        echo "Building library: $LIBRARY"

        # 尝试编译目标，并捕获错误
        if ! xcodebuild -scheme "$LIBRARY" -destination "$destination" -configuration Debug; then
            echo_color_red "Error: Failed to build library: $LIBRARY"
            exit 1
        fi
    done

    echo_color_black "All libraries have been built."
}


# 主函数：执行脚本
main() {
    echo_color_green "开始验证"
    
    # 验证SPM有效性
    validate_swift_package

    echo_color_green "正式验证完成"
}

# 调用主函数
main
